package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.mapper.LeftoverMapper;
import com.ruoyi.system.service.ILeftoverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LeftoverServiceImpl implements ILeftoverService {

    private static final Logger log = LoggerFactory.getLogger(LeftoverServiceImpl.class);


    @Autowired
    private LeftoverMapper leftoverMapper;

    @Autowired
    protected Validator validator;

    @Override
//    @DataSource(value = DataSourceType.SLAVE)
    public List<Leftover> selectLeftoverList(Leftover leftover) {
        return leftoverMapper.selectLeftoverList(leftover);
    }

    @Override
    public Leftover selectLeftoverByTableId(String tableId) {
        return leftoverMapper.selectLeftoverByTableId(tableId);
    }

    @Override
    @Transactional
    public int updateLeftover(Leftover leftover) {
        return leftoverMapper.updateLeftover(leftover);
    }

    /**
     * 导入邊角料数据
     *
     * @param leftoverList    用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importLeftover(List<Leftover> leftoverList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(leftoverList) || leftoverList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Leftover leftover : leftoverList) {
            try {
                BeanValidators.validateWithException(validator, leftover);
                this.insertLeftover(leftover);
                successNum++;
                successMsg.append("<br/>" + successNum + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void insertLeftover(Leftover leftover) {
        // 新增用户信息
        leftoverMapper.insertLeftover(leftover);
    }

    @Override
    public List<LeftoverImport> handleData(List<LeftoverImport> leftoverList) {
        List<LeftoverImport> leftoverList1 = new ArrayList<>();
        for (LeftoverImport leftoverImport : leftoverList) {
            if (leftoverImport != null && leftoverImport.getMaterialId1() != "" && leftoverImport.getMaterialId2() != "" && leftoverImport.getUse() != null && leftoverImport.getUse() != "" && leftoverImport.getMaterialId1() != null && leftoverImport.getModel() != "" && leftoverImport.getModel() != null && !leftoverImport.getModel().equals("外購") && !leftoverImport.getModel().contains("組裝") && !leftoverImport.getModel().contains("制表")) {
                if (new BigDecimal(leftoverImport.getUse()).subtract(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == -1 || leftoverImport.getWeight() == null) {
                    leftoverImport.setWeight(leftoverImport.getUse());
                    leftoverImport.setUse(BigDecimal.ONE.toString());
                }
                if(leftoverImport.getWeight() == null || leftoverImport.getWeight() == ""){
                    leftoverImport.setWeight("0");
                }
                leftoverImport.setMaterialId(leftoverImport.getMaterialId1() + leftoverImport.getMaterialId2());
                leftoverList1.add(leftoverImport);
            }
        }
        queryState(leftoverList1);
        return leftoverList1;
    }

    @Override
    public void updateState(List<LeftoverIdState> leftoverIdStates) {
        for (LeftoverIdState leftoverIdState : leftoverIdStates) {
            leftoverMapper.updateState(leftoverIdState);
        }
    }

    @Override
    public List<Leftover> selectLeftoverIdList(String companyId) {
        return leftoverMapper.selectLeftoverIdList(companyId);
    }

    @Override
    public List<Ztree> selectLeftoverIdTree(String companyId) {
        List<Leftover> leftoverList = leftoverMapper.selectLeftoverIdList(companyId);
        List<Ztree> ztrees = initZtree(leftoverList);
        return ztrees;
    }

    /**
     * 对象转邊角料料號树
     *
     * @param leftoverList 邊角料料號列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Leftover> leftoverList) {
        return initZtree(leftoverList, null);
    }

    /**
     * 对象转部门树
     *
     * @param leftoverList 料號列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Leftover> leftoverList, String checked) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Leftover leftover : leftoverList) {
            Ztree ztree = new Ztree();
            ztree.setpId(0L);
            ztree.setName(leftover.getLeftoverId());
            ztree.setTitle(leftover.getLeftoverId());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public void queryState(List<LeftoverImport> leftoverList) {
        List<Leftover> list = new ArrayList<>();
        for (int i = leftoverList.size() - 1; i > -1; i--) {
            LeftoverImport leftoverImport = leftoverList.get(i);
            String materialId = leftoverImport.getMaterialId();
            int count = leftoverMapper.queryState(materialId);
            if (count > 0) {
                List<String> dbplants = leftoverMapper.selectDbplantById(materialId);
                for (String dbplant : dbplants) {
                    Leftover leftover = new Leftover();
                    leftover.setMaterialId(materialId);
//                    String[] split = leftoverImport.getWeight().split(".");
//                    split[1].length() >= 7 ? split[1].s

                    BigDecimal num = new BigDecimal(leftoverImport.getWeight().substring(0, leftoverImport.getWeight() != "" &&
                            leftoverImport.getWeight().length() - 1 - leftoverImport.getWeight().indexOf(".") >= 7
                            ? leftoverImport.getWeight().indexOf(".") + 8
                            : leftoverImport.getWeight().length()));
                    int index = i - 1;
                    while (index >= 0 && leftoverMapper.queryState(leftoverList.get(index).getMaterialId()) == 0 && (leftoverList.get(index).getWeight().compareTo(leftoverImport.getWeight()) == -1 || leftoverList.get(index).getWeight().compareTo(leftoverImport.getWeight()) == 0)) {
                        BigDecimal inNum = leftoverMapper.selectInNum(leftoverList.get(index).getMaterialId());
                        BigDecimal num1 = num.multiply(new BigDecimal(leftoverList.get(i).getUse()))
                                .subtract(new BigDecimal(leftoverList.get(index).getUse())
                                        .multiply(new BigDecimal(
                                                leftoverList.get(index).getWeight().substring(0, leftoverList.get(index).getWeight() != "" &&
                                                        leftoverList.get(index).getWeight().length() - 1 - leftoverList.get(index).getWeight().indexOf(".") >= 7
                                                        ? leftoverList.get(index).getWeight().indexOf(".") + 8
                                                        : leftoverList.get(index).getWeight().length()))));
                        leftover.setProductId(leftoverList.get(index).getMaterialId());
//                        leftover.setLeftoverNum((num.multiply(inNum)).doubleValue());
                        leftover.setLeftoverNum(num1.doubleValue());
                        leftover.setTableId(UUID.randomUUID().toString());
                        leftover.setDbplant(dbplant);
                        leftoverMapper.insertLeftover(leftover);
                        index--;
                    }
                    i = index + 1;
                }
            }
        }
    }

    @Override
    public List<Leftover> handleNum() {
        List<Leftover> leftoverList = leftoverMapper.selectLeftoverList(new Leftover());
        for (Leftover leftover : leftoverList) {
            BigDecimal bigDecimal = leftoverMapper.selectInNum(leftover.getProductId());
            double x = bigDecimal.doubleValue();
            leftover.setLeftoverNum(x * leftover.getLeftoverNum());
        }
        return leftoverList;
    }

    @Override
    public void updateMaterial(List<LeftoverIdState> leftoverIdStates) {
        for (LeftoverIdState leftoverIdState : leftoverIdStates) {
            leftoverIdState.setDbplant("HFJCD1MAC1");
            if (leftoverIdState.getMaterial().contains("不銹鋼")) {
                leftoverIdState.setMaterial("不銹鋼");
            } else if (leftoverIdState.getMaterial().contains("鋁合金")) {
                leftoverIdState.setMaterial("鋁合金");
            } else if (leftoverIdState.getMaterial().contains("鈦")) {
                leftoverIdState.setMaterial("鈦");
            } else if (leftoverIdState.getMaterial().contains("塑膠")) {
                leftoverIdState.setMaterial("塑膠");
            } else if (leftoverIdState.getMaterial().contains("玻璃")) {
                leftoverIdState.setMaterial("玻璃");
            } else if (leftoverIdState.getMaterial().contains("銅")) {
                leftoverIdState.setMaterial("銅");
            } else {
                leftoverIdState.setMaterial("");
            }
            leftoverMapper.updateMaterial(leftoverIdState);
        }
//        System.out.println("1");
    }

    @Override
    public void updateMes(List<UpdateMes> updateMesList) {
        for (UpdateMes updateMes : updateMesList) {
            if (updateMes.getCommodityName().contains("不銹鋼")) {
                updateMes.setMaterial("不銹鋼");
            } else if (updateMes.getCommodityName().contains("鋁合金")) {
                updateMes.setMaterial("鋁合金");
            } else if (updateMes.getCommodityName().contains("鈦")) {
                updateMes.setMaterial("鈦");
            } else if (updateMes.getCommodityName().contains("塑膠")) {
                updateMes.setMaterial("塑膠");
            } else if (updateMes.getCommodityName().contains("玻璃")) {
                updateMes.setMaterial("玻璃");
            } else if (updateMes.getCommodityName().contains("銅")) {
                updateMes.setMaterial("銅");
            } else {
                updateMes.setMaterial("");
            }
            updateMes.setLeftoverId(updateMes.getAccount() + updateMes.getRecordId());
            leftoverMapper.updateMes(updateMes);
        }
    }

    @Override
    public List<LeftoverQuery> selectLeftoverQueryList(LeftoverQuery leftoverQuery) {
        return leftoverMapper.selectLeftoverQueryList(leftoverQuery);
    }
}
